<template>
  <div>
    <crumbs :BreadCrumb="BreadCrumb"></crumbs>
    <div>
      <el-container style="height: 80vh; border: 1px solid #eee">
        <el-container class="container_box">
          <el-main>
            <div class="header_top">
              <div>
                <el-form
                  :inline="true"
                  :model="searchForm"
                  class="demo-form-inline"
                >
                  <el-form-item label="姓名">
                    <el-input v-model="searchForm.personName" placeholder="姓名" clearable></el-input>
                  </el-form-item>
                  <el-form-item label="科室">
                    <el-cascader
                      :options="deptTree"
                      :props="{ checkStrictly: true,value: 'id', }"
                      v-model="deptIds"
                      clearable>
                    </el-cascader>
                  </el-form-item>
                  <el-form-item>
                    <el-button @click="queryPbPersonsList()">查 找</el-button>
                  </el-form-item>
                  <el-form-item class="staff_form_btn">
                    <el-button type="primary" @click="addlist()"
                    >添加
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>
              <el-divider></el-divider>
            </div>
            <div class="main_box_title">员工信息</div>
            <el-table :data="tableData">
              <el-table-column prop="personCode" label="编号" width="80">
              </el-table-column>
              <el-table-column prop="personName" label="姓名" width="80">
              </el-table-column>
              <el-table-column width="80" prop="sex" label="性别">
                <template slot-scope="scope">{{ scope.row.sex|formatSex }}</template>
              </el-table-column>
              <el-table-column width="120" prop="birthday" label="出生日期">
              </el-table-column>
              <el-table-column width="180" prop="cardid" label="身份证号">
              </el-table-column>
              <el-table-column prop="deptNames" label="所在部门" width="300" show-overflow-tooltip>
              </el-table-column>
              <el-table-column prop="post" label="岗位">
                <template slot-scope="scope">{{formatPost(scope.row.post)}}</template>
              </el-table-column>
              <el-table-column prop="job" label="职务">
                <template slot-scope="scope">{{formatJob(scope.row.job)}}</template>
              </el-table-column>
              <el-table-column
                  width="120"
                  prop="telephone"
                  label="手机号"
              ></el-table-column>
              <el-table-column  label="状态">
                <template slot-scope="scope">
                  {{ scope.row.personStatus | formatStatus }}
                </template>
              </el-table-column>
              <el-table-column prop="editor" label="编写者"></el-table-column>
              <el-table-column width="200" prop="address" label="操作">
                <template slot-scope="scope">
                  <el-button
                      @click="handleClick(scope.row)"
                      type="primary"
                      size="small"
                  >编辑
                  </el-button>
                  <el-button
                      @click="remove(scope.row)"
                      type="danger"
                      size="small"
                  >删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="pagination">
              <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="pageNo"
                  :page-sizes="[10, 20, 30, 40]"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
              >
              </el-pagination>
            </div>
          </el-main>
        </el-container>
      </el-container>
    </div>

    <el-dialog
        title="编辑员工信息"
        :visible.sync="dialogFormVisible"
        width="1000px"
        class="top_dialog"
    >
      <el-form :model="form" label-position="left" ref="ruleForm">
        <div class="add_info">
          <div class="info_l">
            <div>
              <div class="info_sel">
                <div class="info_sel_l">
                  <el-form-item label="姓名" :label-width="formLabelWidth" required>
                    <el-input v-model="form.personName" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="编码" :label-width="formLabelWidth" required>
                    <el-input v-model="form.personCode" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="性别" required>
                    <el-radio-group v-model="form.sex">
                      <el-radio :label="1">男</el-radio>
                      <el-radio :label="2">女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="身份证号" :label-width="formLabelWidth" required>
                    <el-input v-model="form.cardid" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="出生日期" :label-width="formLabelWidth" required>
                    <el-input v-model="form.birthday" autocomplete="off"></el-input>
                  </el-form-item>
                </div>
                <div class="info_sel_r">
                  <avatar :imageUrl="photo" @change="getImage"/>
                </div>
              </div>
              <div class="info_sel">
                <div class="info_sel_l">
                  <el-form-item label="岗位" :label-width="formLabelWidth" required>
                    <el-select
                        class="form_select"
                        v-model="form.post"
                        placeholder="请选择岗位"
                    >
                      <el-option v-for="(v,i) in dict.gwType" :label="v.itemName" :value="v.dictItemId"></el-option>
                    </el-select>
                  </el-form-item>
                </div>
                <div class="info_sel_r">
                  <el-form-item class="" label="职务" :label-width="formLabelWidth" required>
                    <el-select
                        class="form_select"
                        v-model="form.job"
                        size="medium"
                        placeholder="请选择职务"
                    >
                      <el-option v-for="(v,i) in dict.zwType" :label="v.itemName" :value="v.dictItemId"></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </div>
              <div class="info_sel">
                <div class="info_sel_l">
                  <el-form-item label="手机号" :label-width="formLabelWidth" required>
                    <el-input
                        v-model="form.telephone"
                        autocomplete="off"
                    ></el-input>
                  </el-form-item>
                </div>
                <div class="info_sel_r">
                  <el-form-item label="邮箱" :label-width="formLabelWidth">
                    <el-input v-model="form.email" autocomplete="off"></el-input>
                  </el-form-item>
                </div>
              </div>

              <el-form-item label="所属部门" :label-width="formLabelWidth" required>
                <el-row>
                  <el-col :span="20">
                    <el-input v-model="form.deptNames" readonly></el-input>
                  </el-col>
                  <el-col :span="4">
                    <el-button @click="showDeptDialog">所属部门</el-button>
                  </el-col>
                </el-row>
              </el-form-item>
              <el-form-item label="特长/说明" :label-width="formLabelWidth">
                <el-input type="textarea" v-model="form.speciality"></el-input>
              </el-form-item>
              <el-form-item label="人员状态" :label-width="formLabelWidth">
                <el-select v-model="form.personStatus ">
                  <el-option label="正常" :value="1"></el-option>
                  <el-option label="离职" :value="2"></el-option>
                  <el-option label="借调" :value="3"></el-option>
                  <el-option label="临时" :value="4"></el-option>
                </el-select>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editForm('ruleForm')"
        >保 存
        </el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
        title="选择部门"
        :visible.sync="dialogDepts"
        width="1000px"
        class="top_dialog"
    >
      <div style="height: 600px;overflow-y: auto">
        <el-table
            ref="multipleTable"
            :data="departmentList"
            tooltip-effect="dark"
            style="width: 100%"
            :row-key="record=>record.id"
            @selection-change="selectrow"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="label" label="部门名称">
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editUserDetps('ruleForm')">保 存</el-button>
        <el-button @click="dialogDepts = false">取 消</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script lang="ts">
import Avatar from "../common/upload/avatar.vue";
import {formatTimeToStr} from "@src/common/utils/date";

import crumbs from "../../views/Crumbs.vue";
import departments from "../common/departments.vue";

export default {
  components: {
    crumbs,
    departments,
    Avatar,
  },
  data() {
    return {
      dict: {},
      departmentList: [],
      deptTree: [],
      parentDepart: [],
      deptIds: [],
      photo: "",

      total: 0,
      formLabelWidth: "80px",
      dialogFormVisible: false,
      dialogDepts: false,
      searchForm: {},
      pageSize: 10,
      pageNo: 1,
      BreadCrumb: [
        {path: "", name: "基础管理"},
        {path: "/basic/staff", name: "员工信息"},
      ],
      form: {
        deptNames:'',
        deptIds:[],
        personStatus :1,
        sex:1,
      },
      rules: {
        personName: [{required: true, message: "请输入", trigger: "blur"}],
        personCode: [{required: true, message: "请输入", trigger: "blur"}],
        cardid: [{required: true, message: "请输入", trigger: "change"}],
        sex: [{required: true, message: "请输入", trigger: "change"}],
        post: [{required: true, message: "请输入", trigger: "change"}],
        job: [{required: true, message: "请输入", trigger: "change"}],
        telephone: [{required: true, message: "请输入", trigger: "change"}],
      },
      tableData: [],

      multipleSelDepts: [],
    };
  },
  filters: {
    formatSex: function (val) {
      var dict = {1: "男", 2: "女"}
      return dict[val]
    },
    formatStatus: function (val) {
      var dict = {1: "正常", 2: "离职", 3: "借调", 4: "临时"}
      return dict[val]
    },

    formatDate: function (time) {
      if (time != null && time !== "") {
        var date = new Date(time);
        return formatTimeToStr(date, "yyyy-MM-dd hh:mm");
      } else {
        return "";
      }
    },
  },
  created() {
    this.searchDictList()
    this.queryPbPersonsList()
    this.getDeptTree()
  },
  methods: {
    searchDictList() {
      this.$axios.searchDictList({
        codes: ["tyType", "xmType", "jgType", "mzType", "gwType", "zwType", "ybType", "dwxzType", 'zylbType'],
      }).then((res) => {
        if (res.code === "00000") {
          res.data.forEach(v => {
            this.dict[v.dictCode] = v.items
          })
        }
      });
    },
    formatPost (val) {
      const map = {}
      this.dict.gwType.forEach(v=>{
        map[v.dictItemId] = v.itemName
      })
      let res = val
      if(map[val] !== undefined){
        res = map[val]
      }
      return res
    },
    formatJob (val) {
      const map = {}
      this.dict.zwType.forEach(v=>{
        map[v.dictItemId] = v.itemName
      })
      if(map[val] !== undefined){
        return map[val]
      }
      return val
    },
    queryPbPersonsList() {
      console.log("deptIds:",this.deptIds)
      if (this.deptIds.length > 0) {
        this.searchForm.deptIds = [this.deptIds[this.deptIds.length - 1]]
      }else {
        delete this.searchForm.deptIds
      }
      this.doGetList(this.searchForm)
    },
    doGetList(req){
      this.tableData = []
      this.$axios.queryPbPersonsList(req).then((res) => {
        if (res.code == "00000") {
          res.data.records.forEach(res=>{
            let names = []
            res.pbDepartmentsList.forEach(v=>{
              names.push(v.deptName)
            })
            res['deptNames'] = names.join(",")
            this.tableData.push({...res})
          })
          this.total = res.data.total;
        }
      });
    },

    showDeptDialog() {
      this.getDeptTree()
      this.dialogDepts = true
    },
    selectrow(val) {
      this.multipleSelDepts = val;
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleClick(row) {
      this.$axios.queryPerson({personId: row.id,})
        .then((res) => {
          if (res.code == "00000") {
            this.id = res.data.id;
            let resData = res.data;
            let names = []
            let deptIds =[]
            resData.pbDepartmentsList.forEach(v=>{
              names.push(v.deptName)
              deptIds.push(v.id)
            })
            this.form = {
              ...resData,
              deptNames:names.join(","),
              deptIds:deptIds,
              property: `${resData.property}`
            };
          }
        });
      this.dialogFormVisible = true;
    },
    getDeptTree() {
      this.departmentList = []
      this.$axios.getDepartTreeList({}).then((res) => {
        if (res.code == "00000") {
          if (res.data.length > 0) {
            this.deptTree = res.data
            let departmentList = res.data[0].children;
            var list = []
            departmentList.forEach(v=>{
              const item = {id:v.id, label:v.label}
              if(this.form.deptIds && this.form.deptIds.indexOf(v.id)>=0){
                list.push(item)
              }
              this.departmentList.push(item)
            })
            this.toggleSelection(list)
          }
        }
      });
    },
    editUserDetps() {
      this.form.deptIds = []
      this.form.deptNames = ""
      let names = []
      this.multipleSelDepts.forEach(v => {
        names.push(v.label)
        this.form.deptIds.push(v.id)
      })
      this.form.deptNames = names.join(",")
      this.dialogDepts = false
    },

    getImage(e) {
      this.photo = e;
      this.form.photo = e;
    },
    editForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const formData = {
            ...this.form,
          };
          if (this.id == null) {
            this.$axios.insertPerson({...formData})
              .then((res) => {
                if (res.code == "00000") {
                  this.$message({
                    type: "success",
                    message: res.msg,
                  });
                  this.dialogFormVisible = false;
                  this.queryPbPersonsList()
                }
              });
          } else {
            this.$axios
                .updatePerson({
                  id: this.id,
                  ...formData,
                })
                .then((res) => {
                  if (res.code == "00000") {
                    this.$message({
                      type: "success",
                      message: res.msg,
                    });
                    this.queryPbPersonsList()
                    this.dialogFormVisible = false;
                  }
                });
          }
        }
      });
      this.queryPbPersonsList();
    },
    addlist() {
      this.dialogFormVisible = true;
      this.id = null
      this.form = {}
    },

    remove(row) {
      this.$confirm("此操作将删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$axios
            .deletePersonById({
              personId: row.id,
            })
            .then((res) => {
              if (res.code == "00000") {
                this.$message({
                  type: "success",
                  message: res.msg,
                });
                this.queryPbPersonsList();
              }
            });
      });
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },

    // 每页几条
    handleSizeChange(val) {
      this.pageSize = val
      const req = {
        ...this.searchForm,
        pageSize:this.pageSize,
        pageNo:this.pageNo,
      }
      this.doGetList(req)
    },
    // 第几页
    handleCurrentChange(val) {
      this.pageNo = val
      const req = {
        ...this.searchForm,
        pageSize:this.pageSize,
        pageNo:this.pageNo,
      }
      this.doGetList(req)
    },
  },
};
</script>

<style scoped>
.main_box_title {
  background: #fff;
  padding: 10px;
}

.aside_box_title {
  margin: 0px 8px 10px;
  /* text-align: center; */
}

.header_top .el-divider--horizontal {
  margin-top: 0px;
}

.el-main {
  padding: 0px;
  padding-left: 20px;
}

.staff_form_btn {
  margin-left: 20px;
}

.info_l {
  width: 80%;
  margin: 0px auto;
}

.info_l_input {
  width: 82%;
}

.info_l_button {
  margin-left: 10px;
}

.info_sel_r_groupn {
  margin-left: 40px;
}

.info_sel_r_group {
  margin-left: 10px;
}

.info_sel {
  display: flex;
}

.info_sel_l {
  width: 50%;
}

.info_sel_r {
  width: 50%;
  margin-left: 50px;
}

.info_sel_r_img {
  width: 180px;
  height: 220px;
  margin: 0px auto;
}

.avatar-uploader {
  margin: 0px auto;
  text-align: center;
}

.info_l /deep/ .el-select {
  width: 100%;
}

.info_l_head {
}

.pagination {
  text-align: center;
}
</style>
